import { FC, useState, useEffect } from "react";
import { AtAvatar, AtButton } from "taro-ui";
import { Button } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { fetchUserInfo, uploadImage } from "../../utils/api";

interface UploadAvatarProps {
  circle?: boolean;
  avatar?: string;
  uploadImageClick?(): void;
}

type UserInfoType = {
  avatar: string;
  nickName?: string;
};

const UploadAvatar: FC = () => {
  const [userInfo, setUserInfo] = useState<UserInfoType>({
    avatar: "",
    nickName: "zhansan",
  });
  // 头像上传函数
  const handleUploadImage = () => {
    Taro.chooseImage({
      success: async (res) => {
        const tempFilePaths = res.tempFilePaths;
        const response = await uploadImage({
          msg: "native",
          paths: tempFilePaths,
        });
        console.log("上传图片：", response.data.url);
        // 为什么要把userInfo拓展进来?
        // useState中的数据，会合并更新，也就是一个改变，都会改变，如果不想让其他数据改变，那就需要把这个数据拓展进来。
        // 下面的更新，会有avatar的新值和nickName的原始值
        setUserInfo({ ...userInfo, avatar: response.data.url });
      },
    });
  };

  useEffect(() => {
    console.log("useInfo:", userInfo);
  }, [userInfo]);

  const getUserInfo = async () => {
    const res = await fetchUserInfo();
    console.log("reS:", res.userInfo.avatarUrl, res.userInfo.nickName);
    // 为什么这个地方不用拓展？
    setUserInfo({
      nickName: res.userInfo.nickName,
      avatar: res.userInfo.avatarUrl,
    });
  };
  return (
    <>
      {userInfo.avatar ? (
        <>
          <AtAvatar circle={true} image={userInfo.avatar}></AtAvatar>
          <Button onLongPress={handleUploadImage}>长按上传图片</Button>
        </>
      ) : (
        <>
          {/* <Button onLongPress={}></Button> */}
          <AtButton onClick={handleUploadImage} type="primary" size="small">
            上传图片
          </AtButton>
          <AtButton onClick={getUserInfo} type="primary" size="small">
            获取用户信息
          </AtButton>
        </>
      )}
    </>
  );
};

export default UploadAvatar;
